package com.zc.app.sys.controller;

import com.github.pagehelper.PageInfo;
import com.zc.app.sys.dao.peer.SystemUserPeer;
import com.zc.app.sys.service.SystemUserService;
import com.zc.framework.common.bean.AjaxResult;
import com.zc.framework.common.bean.MyPageInfo;
import com.zc.framework.system.BaseController;
import com.zc.framework.utils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by zc on 2016/11/24.
 */
@Controller
@RequestMapping("/sys/user")
public class SystemUserController  extends BaseController {

    private static Logger logger = LogManager.getLogger(SystemUserController.class);

    @Autowired
    private SystemUserService systemUserService;

    @InitBinder({ "systemUser" })
    public void initBinderSystemUser(WebDataBinder binder) {
        //注册自定义的属性编辑器
        //1、日期
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CustomDateEditor dateEditor = new CustomDateEditor(df, true);
        //表示如果命令对象有Date类型的属性，将使用该属性编辑器进行类型转换
        binder.registerCustomEditor(Date.class, dateEditor);
        binder.setFieldDefaultPrefix("systemUser.");
    }


//    @RequiresPermissions("sysuser:list:view")
    @RequestMapping(value = "/", method = {RequestMethod.GET})
    public ModelAndView index(SystemUserPeer userPeer){
        ModelAndView modelAndView = new ModelAndView("/admin/sys/user/index");
        if(userPeer==null){
            userPeer = new SystemUserPeer();
        }
        PageInfo<SystemUserPeer> pageInfo = systemUserService.querySysUsers(userPeer, userPeer.getPage(),userPeer.getRows());
        logger.info("pageInfo:"+pageInfo);
        modelAndView.addObject("pageInfo",pageInfo);
        return modelAndView;
    }


    @RequestMapping(value = "/edit", method = {RequestMethod.GET})
    public ModelAndView edit(@RequestParam(value = "pageType",required = false)String pageType,
                             @RequestParam(value = "accountId",required = false)Integer accountId){
        ModelAndView modelAndView = new ModelAndView("/admin/sys/user/edit");
        SystemUserPeer userBean = new SystemUserPeer();
        if("edit".equals(pageType)
                && accountId!=null){
            userBean = systemUserService.selectByPrimaryKey(accountId);
        }
        modelAndView.addObject("systemUser", userBean);
        modelAndView.addObject("pageType",pageType);
        return modelAndView;
    }

    @RequestMapping(value = "/view", method = {RequestMethod.GET})
    public ModelAndView view(@RequestParam(value = "accountId",required = false)Integer accountId){
        ModelAndView modelAndView = new ModelAndView("/admin/sys/user/view");
        SystemUserPeer userBean = new SystemUserPeer();
        if(accountId!=null){
            userBean = systemUserService.selectByPrimaryKey(accountId);
        }
        modelAndView.addObject("systemUser", userBean);
        return modelAndView;
    }

    @RequiresPermissions("sysuser:list:view")
    @RequestMapping(value = "/list", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public MyPageInfo<SystemUserPeer> search(SystemUserPeer userPeer) throws InvocationTargetException, IllegalAccessException {
        if(userPeer==null){
            userPeer = new SystemUserPeer();
        }
        MyPageInfo<SystemUserPeer> pageInfo = systemUserService.querySysUsers(userPeer, userPeer.getPage(),userPeer.getRows());
        logger.info("pageInfo:"+pageInfo);
        return pageInfo;
    }

    @RequestMapping(value = "/users", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public List<SystemUserPeer> users(SystemUserPeer userPeer) throws InvocationTargetException, IllegalAccessException {
        if(userPeer==null){
            userPeer = new SystemUserPeer();
        }
        return systemUserService.querySysUsers(userPeer);
    }


    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult login(@Validated @ModelAttribute(value = "systemUser") SystemUserPeer systemUser,
                            @RequestParam(value = "pageType",required = false)String pageType,
                            HttpServletRequest request,
                            HttpServletResponse response, Model model) {

        SystemUserPeer user = systemUserService.getCurrentUser();

        if("edit".equals(pageType)){
            if (systemUser.getAccountId()==null) {
                return fail(false, "账号ID不能为空!");
            }
            systemUser.setUpdateBy(user.getUserName());
            systemUserService.updateByPrimaryKeySelective(systemUser);
            return success(true);
        }

        if (StringUtils.isEmpty(systemUser.getLoginName())) {
            return fail(false, "账号不能为空!");
        }
        if (StringUtils.isEmpty(systemUser.getLoginPassword())) {
            return fail(false, "密码不能为空!");
        }

        systemUser.setCreateBy(user.getUserName());
        systemUser.setUpdateBy(user.getUserName());
        systemUserService.createUser(systemUser);
        return success(true);
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult delete(@RequestParam(value = "accountId")Integer[] accountIds,
                            HttpServletRequest request,
                            HttpServletResponse response, Model model) {

        if(accountIds==null || accountIds.length==0){
            return fail(false,"用户ID不能为空");
        }
        for(Integer accountId: accountIds){
            systemUserService.deleteByPrimaryKey(accountId);
        }
        return success(true);
    }



}
